package xyz.molzhao.alink.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.text.StrPool;
import xyz.molzhao.alink.domain.StorageContext;

import java.util.*;

/**
 * 文件工具类
 */
public class FileUtils {
    private FileUtils() {

    }

    static final List<String> NO_NEED_DOWNLOAD_FILE_EXT_NAME = Arrays.asList("png", "jpg", "jpeg", "gif", "pdf");


    public static String addExtName(String fileName, String extName) {
        return fileName + StrPool.DOT + extName;
    }

    public static String fillFileName(StorageContext context) {
        String fileName = CharSequenceUtil.isBlank(context.getFileName()) ? context.getFile().getOriginalFilename() : context.getFileName();

        // 如果新文件名没有扩展名则加上旧文件的扩展名
        if (CharSequenceUtil.isBlank(FileUtil.extName(fileName))) {
            fileName = addExtName(fileName, FileUtil.extName(context.getFile().getOriginalFilename()));
        }

        String filePath = String.format("%s/%s", context.getDirectory(), fileName);
        if (context.isTimeFlag()) {
            filePath = String.format("%s/%s/%s", context.getDirectory(),
                    DateUtil.format(new Date(), "YYMMDD"),
                    DateUtil.date().getTime() + fileName);
        }
        return filePath;
    }

    /**
     * 图片、pdf等不需要下载，直接在浏览器打开
     * @param fileName
     * @return
     */
    public static boolean notNeedDownload(String fileName) {
        return Boolean.TRUE.equals(NO_NEED_DOWNLOAD_FILE_EXT_NAME.stream().anyMatch(FileUtil.extName(fileName)::equalsIgnoreCase));
    }

}
